package com.zyg.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.alibaba.fastjson2.JSON;
import com.zyg.pojo.User;
import com.zyg.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("/")
    public String login() {
        return "login";
    }

    @RequestMapping("/codeImage")
    @ResponseBody
    public String code(HttpSession session) {
        // 移除上一次的验证码
        session.removeAttribute("code");
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        // 将验证码放入session
        session.setAttribute("code", captcha.getCode());
        // 将验证码转换为base64
        String imageBase64 = captcha.getImageBase64();
        return JSON.toJSONString(imageBase64);
    }

    @PostMapping("/login")
    @ResponseBody
    public String login(User user, @RequestParam("code") String code, HttpSession session) {
        String sessionCode = (String) session.getAttribute("code");
        if (sessionCode != null && sessionCode.equalsIgnoreCase(code)) {
            // 判断用户名以及密码是否正确
            boolean flag = userService.login(user);
            if (flag) {
                return "success";
            } else {
                return "error";
            }
        } else {
            return "error";
        }

    }
}
